import { AssetType, IAssetInfo, IAssetObject } from './types';
import { generate } from 'shortid';
import pluginsStore from '../store/plugins';
import { defineStore } from 'pinia';
// @ts-ignore
import { cloneDeep } from 'lodash';
import db from '../database';
import { Emitter } from '@/ui-kit/index';
import { Msg } from '../msg';
import eventsStore from './events';
import { scenesStore } from './scenes';
import { calcNextIndex } from './util';

export interface IAssetStore {
    assets: IAssetInfo[];
}

const BuiltInObj: IAssetInfo[] = [
    // {
    //     id:'system',
    //     group: 'test',
    //     type:'',
    //     label: '系统',
    //     icon: 'icon-text',
    //     desc: 'system',
    // },
];
const assetsStore = defineStore('assets', {
    state: (): IAssetStore => {
        return {
            assets: [],
        };
    },
    actions: {
        toConfig() {
            return {
                key: 'assets',
            };
        },
        filterAssetByType(type: AssetType): IAssetInfo[] {
            const ret: IAssetInfo[] = [];
            this.assets.forEach(asset => {
                if (asset.type === type) {
                    ret.push(asset);
                }
            });
            return ret;
        },
        init(data: IAssetStore) {
            if (data) {
                this.assets = data.assets;
            }
        },
        renameAsset(id: string, name: string) {
            const ret = this.getAsset(id);
            if (ret && name.length && ret.name !== name) {
                const reg = new RegExp(/^[\u4E00-\u9FA5A-Za-z0-9_]+$/);
                if (reg.test(name)) {
                    ret.name = name;
                    Emitter.emit(Msg.AssetRename, id);
                    db.save();
                    return true;
                } else {
                    console.log('无效的名字');
                }
            }
            return false;
        },
        addEvent() {
            const sheetID = generate();
            const idx = this._getAssetNextIndex(AssetType.Event);
            this.assets.push({
                id: generate(),
                name: '新的事件表' + idx,
                type: AssetType.Event,
                data: sheetID,
            });
            eventsStore().createSheet(sheetID);
            db.save();
        },
        addScene() {
            const id = generate();
            const idx = this._getAssetNextIndex(AssetType.Scene);
            this.assets.push({
                id: generate(),
                name: '新的场景' + idx,
                type: AssetType.Scene,
                data: id,
            });
            scenesStore().addScene(id);
            db.save();
        },
        _getAssetNextIndex(type: AssetType): number {
            const arr = this.filterAssetByType(type);
            const names = arr.map(item => {
                return item.name;
            });
            return calcNextIndex(names);
        },
        removeScene(id: string) {
            const item = this._removeAsset(id);
            if (item) {
                Emitter.emit(Msg.RemoveSceneAsset, item);
                scenesStore().removeScene(item.data);
                db.save();
            }
        },
        _removeAsset(id: string): IAssetInfo | null {
            const idx = this.assets.findIndex(el => el.id === id);
            if (idx !== -1) {
                return this.assets.splice(idx, 1)[0];
            }
            return null;
        },
        removeEvent(id: string) {
            const item = this._removeAsset(id);
            if (item) {
                Emitter.emit(Msg.RemoveEventAsset, item);
                eventsStore().removeSheet(item.data);
                db.save();
            }
        },
        addObjectBehavior(id: string, bundle: string) {
            const asset = this.getAsset(id);
            if (asset && asset.type === AssetType.Object) {
                const data = asset as IAssetObject;
                if (!data.data.behaviors) {
                    data.data.behaviors = [];
                }
                if (!data.data.behaviors.find(el => el === bundle)) {
                    data.data.behaviors.push(bundle);
                }
                db.save();
            }
        },
        removeObjectBehavior(id: string, bundle: string) {
            const asset = this.getAsset(id);
            if (asset && asset.type === AssetType.Object) {
                const data = asset as IAssetObject;
                const behaviors = data.data.behaviors;
                if (behaviors) {
                    const index = behaviors.findIndex(el => el === bundle);
                    if (index !== undefined) {
                        behaviors.splice(index, 1);
                    }
                }
            }
        },
        addObject(bundle: string): IAssetObject | null {
            const ret = pluginsStore().getObjectByID(bundle);
            if (ret) {
                const item: IAssetObject = {
                    id: generate(),
                    name: ret.info?.name || '新的对象',
                    icon: ret.info?.icon || '',
                    type: AssetType.Object,
                    data: {
                        bundle,
                        vars: [],
                        behaviors: [],
                    },
                };
                this.assets.push(item);
                return item;
            }
            return null;
        },
        removeObject(id: string) {
            const item = this._removeAsset(id);
            if (item) {
                Emitter.emit(Msg.RemoveObjectAsset, item);
                db.save();
            }
        },
        getAsset(id: string): IAssetInfo | null {
            return this.assets.find(el => el.id === id) || null;
        },
        changeObjectInstance() {
        
        },
        addVariable(variable: sail.Variable, id: string) {
            const ret = this.getAsset(id);
            if (ret) {
                const data = ret as IAssetObject;
                if (!data.data.vars) {
                    data.data.vars = [];
                }
                data.data.vars.push(variable);
                db.save();
            }
        },
        modifyVariableValue(objID: string, id: string, val: sail.Variable) {
            const ret = this.getAsset(objID);
            if (ret) {
                const data = ret as IAssetObject;
                const item = data.data.vars.find(el => el.id === id);
                if (item) {
                    item.desc = val.desc;
                    item.value = val.value;
                    item.name = val.name;
                    // type, id 不允许更换
                    db.save();
                }
            }
        },
        removeVariable(variable: sail.Variable, id: string) {
            const ret = this.getAsset(id);
            if (ret) {
                const data = ret as IAssetObject;
                const del = this._removeVar(data.data.vars, variable.id);
                if (del) {
                    db.save();
                }
            }
        },
        _removeVar(vars: sail.Variable[], id: string) {
            const index = vars.findIndex(el => el.id === id);
            if (index !== undefined && index !== -1) {
                return vars.splice(index, 1)[0];
            }
            return null;
        },
    },
});
export default assetsStore;